//
//  KStockAPI.swift
//  TestAPIManager
//
//  Created by yq on 2020/10/21.
//  Copyright © 2020 杨庆. All rights reserved.
//

import Foundation

import RxSwift
import RxCocoa
import Moya
import HandyJSON
struct YeloApi<Target: TargetType> {
    
    var provider = MoyaProvider<Target>()//.make()
    
    @discardableResult
    func request<Model>(_ target: Target, mapModel: Model.Type, completion: @escaping (MoyaResult<Model>) -> Void) -> Cancellable {
        return provider.request(target) { result in
            switch result {
            case .success(let resp):
                completion(resp.mapModel(mapModel))
            case .failure(let err):
                completion(.failure(err.errorCode, kErrmsg_NetworkAnomaly))
            }
        }
    }
    
    func request<Model>(_ target: Target, mapModel: Model.Type) -> Observable<MoyaResult<Model>> {
        return provider.rx
            .request(target)
            .mapModel(mapModel)
            .catchErrorJustReturn(.failure(-999, kErrmsg_NetworkAnomaly))
    }
}

//let kCodeApi = YeloApi<YeloCodeTarget>()
//let kLoginApi = YeloApi<LoginTarget>()
//let kStockApi = YeloApi<StockTarget>()
let kStockInOutApi = YeloApi<StockInOutTarget>()
//let kMineApi = YeloApi<MineTarget>()



class myclassAPI<Target:TargetType> {

    var provider = MoyaProvider<Target>()
    
    func request<Model>(target:Target,modelType:Model.Type, completion:@escaping (YMoyaResult<Model>) -> Void) {

        provider.request(target) { (result) in
            switch result {
            case .success(let resp):
                completion(self.transformToModel(from: resp, type: modelType))
            case .failure(let err):
                print(err.errorCode)
                completion(.failure(err.errorCode, "网络错误"))
            }
        }
    }
    
    

    func transformToModel<T>(from resp: Response, type:T.Type)-> YMoyaResult<T> {
        
        guard let _ = try? resp.filterSuccessfulStatusCodes() else {
            return .failure(resp.statusCode, "服务器请求失败")
        }
        
        let data = resp.data
        
        // 判断数据格式
        guard JSONSerialization.isValidJSONObject(data) else {
            return .failure(resp.statusCode, "数据无效")
        }
        
        // 转成json
        guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) else {return .failure(resp.statusCode, "数据无效")}
        guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)else {return .failure(resp.statusCode, "数据无效")}
        
        // 转成 json string
        guard let jsonStr = String(data: jsonData, encoding: .utf8) else {
            return .failure(resp.statusCode, "数据无效")
        }
        print(jsonStr)
        
        // json -> model
        guard let model = JSONDeserializer<YBaseData<T>>.deserializeFrom(json: jsonStr)?.data else {
            return .failure(resp.statusCode, "转模型失败,数据无效")
        }
        return .success(model)
    }
    
    
    
}


struct YBaseData<T>:HandyJSON {
     var errcode: Int = -1
    var errmsg: String = NSLocalizedString("Network_errorCode_null", comment:"")
    var data:T? = nil
}

enum YMoyaResult<T> {
    case success(T)
    case failure(Int,String)
}
    

